package com.myrslok;

import com.myrslok.util.ZipUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class MZipFile {

    private static final Logger logger = LoggerFactory.getLogger(MZipFile.class);

    protected final String file;
    private boolean verbose = false;

    public MZipFile(final String file) {
        this.file = file;
    }

    public void setVerbose(final boolean verbose) {
        this.verbose = verbose;
    }

    /**
     * For example, this method extracts <code>core/src/test/resources/junit4.10.zip</code> into
     * <code>core/src/test/resources</code>.
     */
    public void extractToLocation() {
        final File parentFile = new File(file).getParentFile();
        if (parentFile != null) {
            extractTo(parentFile.getPath());
        } else {
            extractTo(".");
        }
    }

    public void extractTo(@NotNull final String to) {
        if (verbose) {
            logger.info("Extracting " + file + " to " + to);
        }
        final File toDir = prepareDest(to);
        try {
            unArchive(toDir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected void unArchive(@NotNull final File toDir) throws IOException {
        ZipUtil.unzip(new File(file), toDir);
    }

    private File prepareDest(@NotNull final String to) {
        final File toDir = new File(to);
        toDir.mkdirs();
        return toDir;
    }

}
